package cc.woori.mobile;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cc.woori.mobile.bean.NoteEntity;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

public class ModifyNoteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {
	doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {

	String mode = req.getParameter("mode");
	String reqKey = req.getParameter("key");
	Key key = KeyFactory.stringToKey(reqKey);

	PersistenceManager pm = PMF.get().getPersistenceManager();
	NoteEntity en = pm.getObjectById(NoteEntity.class, key);
	try {
	    if (mode.equalsIgnoreCase("delete")) {
		pm.deletePersistent(en);
	    } else if (mode.equalsIgnoreCase("edit")) {
		String title = req.getParameter("title");
		Text body = new Text(req.getParameter("body").replaceAll("\\n",
			"<br />"));

		Transaction tx = pm.currentTransaction();
		tx.begin();

		en.setTitle(title);
		en.setBody(body);

		pm.makePersistent(en);
		tx.commit();
	    }
	} finally {
	    if (pm != null) {
		pm.close();
	    }
	}

	RequestDispatcher view = req
		.getRequestDispatcher("/admin/adminNotice.jsp");
	view.forward(req, resp);
    }
}
